<template>
  <div v-if="open" class="fixed inset-0 bg-black/40 grid place-items-center p-4 z-50">
    <div class="card w-full max-w-lg">
      <div class="text-lg font-semibold mb-2">{{ isEditMode ? '编辑哭闹记录' : '记录哭闹' }}</div>
      <form class="space-y-3" @submit.prevent="save">
        <label class="block">
          <span class="text-sm">开始时间</span>
          <input class="input mt-1" type="datetime-local" v-model="startLocal" />
        </label>
        <label class="block">
          <span class="text-sm">结束时间</span>
          <input class="input mt-1" type="datetime-local" v-model="endLocal" />
        </label>

        <div>
          <div class="text-sm mb-2">原因推测</div>
          <div class="flex flex-wrap gap-2">
            <button v-for="r in reasonsOptions" :key="r.value" type="button"
              class="px-3 py-1 rounded"
              :class="selectedReasons.includes(r.value) ? 'bg-primary text-white' : 'bg-bg'"
              @click="toggleReason(r.value)">{{ r.label }}</button>
          </div>
        </div>

        <div>
          <div class="text-sm mb-2">安抚方式</div>
          <div class="flex flex-wrap gap-2">
            <button v-for="s in sootheOptions" :key="s.value" type="button"
              class="px-3 py-1 rounded"
              :class="selectedSoothe.includes(s.value) ? 'bg-primary text-white' : 'bg-bg'"
              @click="toggleSoothe(s.value)">{{ s.label }}</button>
          </div>
        </div>

        <label class="block">
          <span class="text-sm">备注</span>
          <textarea class="input mt-1" rows="3" placeholder="可输入备注...（可选）" v-model="note" />
        </label>

        <div class="flex gap-2">
          <button type="submit" class="btn-primary flex-1" :disabled="loading">
            {{ loading ? '保存中...' : '保存' }}
          </button>
          <button type="button" class="btn-accent flex-1" @click="$emit('update:open', false)">取消</button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue';
import { useUserStore } from '../stores/user';
import { API_CONFIG } from '../services/api';

// 临时解决方案：直接定义函数
async function createCry(payload: any) {
  const token = localStorage.getItem('auth_token');
  console.log('CryModal createCry - token:', token);
  const resp = await fetch(`${API_CONFIG.BASE_URL}/api/records/cry`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token || ''}`
    },
    body: JSON.stringify(payload)
  });
  if (!resp.ok) {
    const errorText = await resp.text();
    throw new Error(`HTTP ${resp.status}: ${errorText}`);
  }
  return await resp.json();
}

async function updateCry(payload: any) {
  const token = localStorage.getItem('auth_token');
  console.log('CryModal updateCry - token:', token);
  const resp = await fetch(`${API_CONFIG.BASE_URL}/api/records/cry/${payload.id}`, {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token || ''}`
    },
    body: JSON.stringify(payload)
  });
  if (!resp.ok) {
    const errorText = await resp.text();
    throw new Error(`HTTP ${resp.status}: ${errorText}`);
  }
  return await resp.json();
}

const props = defineProps<{ 
  open: boolean;
  editData?: any; // 编辑时的数据
}>();
const emit = defineEmits<{ 
  (e: 'update:open', v: boolean): void;
  (e: 'saved'): void;
}>();
const userStore = useUserStore();

const startLocal = ref<string>('');
const endLocal = ref<string>('');
const selectedReasons = ref<string[]>([]);
const selectedSoothe = ref<string[]>([]);
const note = ref<string>('');
const loading = ref(false);
const isEditMode = computed(() => !!props.editData);

const reasonsOptions = [
  { value: 'HUNGRY', label: '饿了' },
  { value: 'SLEEPY', label: '困了' },
  { value: 'WET', label: '尿布湿了' },
  { value: 'COLD', label: '冷了' },
  { value: 'HOT', label: '热了' },
  { value: 'BORED', label: '无聊' },
  { value: 'OVERSTIMULATED', label: '过度刺激' },
  { value: 'SICK', label: '生病' },
  { value: 'OTHER', label: '其他' }
];

const sootheOptions = [
  { value: 'FEED', label: '喂奶' },
  { value: 'ROCK', label: '摇晃' },
  { value: 'SING', label: '唱歌' },
  { value: 'WALK', label: '散步' },
  { value: 'BATH', label: '洗澡' },
  { value: 'MASSAGE', label: '按摩' },
  { value: 'MUSIC', label: '音乐' },
  { value: 'OTHER', label: '其他' }
];

function toggleReason(value: string) {
  const index = selectedReasons.value.indexOf(value);
  if (index > -1) {
    selectedReasons.value.splice(index, 1);
  } else {
    selectedReasons.value.push(value);
  }
}

function toggleSoothe(value: string) {
  const index = selectedSoothe.value.indexOf(value);
  if (index > -1) {
    selectedSoothe.value.splice(index, 1);
  } else {
    selectedSoothe.value.push(value);
  }
}

watch(
  () => props.open,
  (v) => {
    if (v) {
      if (props.editData) {
        // 编辑模式：填充现有数据
        const startTime = new Date(props.editData.startTime);
        startLocal.value = new Date(startTime.getTime() - startTime.getTimezoneOffset() * 60000)
          .toISOString()
          .slice(0, 16);
        if (props.editData.endTime) {
          const endTime = new Date(props.editData.endTime);
          endLocal.value = new Date(endTime.getTime() - endTime.getTimezoneOffset() * 60000)
            .toISOString()
            .slice(0, 16);
        } else {
          endLocal.value = '';
        }
        selectedReasons.value = props.editData.reasons || [];
        selectedSoothe.value = props.editData.sootheWays || [];
        note.value = props.editData.note || '';
      } else {
        // 新建模式：使用当前时间
        const now = new Date();
        startLocal.value = new Date(now.getTime() - now.getTimezoneOffset() * 60000)
          .toISOString()
          .slice(0, 16);
        endLocal.value = '';
        selectedReasons.value = [];
        selectedSoothe.value = [];
        note.value = '';
      }
    }
  }
);

async function save() {
  if (!userStore.currentBabyId) {
    alert('请先选择宝宝');
    return;
  }

  if (!startLocal.value) {
    alert('请填写开始时间');
    return;
  }

  try {
    loading.value = true;
    const startTime = new Date(startLocal.value).toISOString();
    const endTime = endLocal.value ? new Date(endLocal.value).toISOString() : undefined;

    if (isEditMode.value) {
      // 编辑模式：调用更新API
      await updateCry({
        id: props.editData.id,
        babyId: userStore.currentBabyId,
        startTime,
        endTime,
        reasons: selectedReasons.value,
        sootheMethods: selectedSoothe.value,
        note: note.value || undefined
      });
    } else {
      // 新建模式：调用创建API
      await createCry({
        babyId: userStore.currentBabyId,
        startTime,
        endTime,
        reasons: selectedReasons.value,
        sootheMethods: selectedSoothe.value,
        note: note.value || undefined
      });
    }

    emit('saved');
    emit('update:open', false);
  } catch (error) {
    console.error('保存哭闹记录失败:', error);
    alert('保存失败，请重试');
  } finally {
    loading.value = false;
  }
}
</script>

<style scoped></style>